#ifndef QVCCONTEX_H
#define QVCCONTEX_H

#include <QObject>
#include <QCoreApplication>
#include <memory>
#include <QTimer>
#include <sharememory.h>

template <typename T>
class Serialize{
public:
    T operator() (const QByteArray& data) {
        T value;

        if(data.size() != sizeof (T)) {
            return value;
        }

        std::memcpy(&value, data.data(), data.size());

        return value;
    }

    QByteArray operator() (T&& data) {

        QByteArray value(sizeof (data), 0);

        std::memcpy(value.data(), &data, value.size());

        return value;
    }
};


class QVCContex : public QCoreApplication
{
public:
    QVCContex(int argc, char** argv);

    void setTransfer(std::unique_ptr<Transfer> transfer) {
        this->transfer = std::move(transfer);
    }

    template<typename T, size_t hz = 1>
    void subscribe(const QString& topic, std::function<void(const T&)> fun) {
        QTimer* timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, [this, fun, topic]{
            T val = Serialize<T>{}(transfer->recive(topic, sizeof (T)));
            fun(val);
        });

        timer->start(1000 / hz);
    }

    template<typename T>
    size_t publish(const QString& topic, T&& data) {
        return transfer->send(topic, Serialize<T>{}(std::forward<T>(data)));
    }

private:
    std::unique_ptr<Transfer> transfer;
};


#endif // QVCCONTEX_H
